#!/bin/bash

# 获取当前脚本的绝对路径
SCRIPT_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"
SHELL_FILE_DIR=$(dirname $SCRIPT_PATH)
cd $SHELL_FILE_DIR
export GIT_PUSH_URL="git@gitcode.com:hq_make/platform_module.git"
<<<<<<< HEAD

# 配置 SSH 命令：接受新主机密钥，避免交互
export GIT_SSH_COMMAND="ssh -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=~/.ssh/known_hosts"

# 确保 .ssh 目录存在
mkdir -p ~/.ssh

# 可选：预加载 gitcode.com 的 host key（更可靠）
ssh-keyscan -t rsa gitcode.com 2>/dev/null >> ~/.ssh/known_hosts 2>/dev/null || true
=======
# 配置 SSH 命令：接受新主机密钥，避免交互
export GIT_SSH_COMMAND="ssh -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=~/.ssh/known_hosts"
# 可选：预加载 gitcode.com 的 host key（更可靠）
ssh-keyscan -t rsa gitcode.com 2>/dev/null >> ~/.ssh/known_hosts 2>/dev/null || true
# 确保 .ssh 目录存在
mkdir -p ~/.ssh


>>>>>>> 6937f09 (推送默认分支)

if [ ! -d ".git" ]; then
  echo "Initializing Git repository..."

  # 初始化仓库
  git config --global init.defaultBranch master
  git init

  GITDIR=$(pwd)
  git config --global --add safe.directory "$GITDIR"

  git remote add origin "$GIT_PUSH_URL"

  # 用户配置
  git config --global user.name "qqgitcode"
  git config --global user.email "qqgitcode@noreply.gitcode.com"

  # 检查远程是否存在 master 分支
  if git ls-remote --exit-code --heads origin master > /dev/null 2>&1; then
<<<<<<< HEAD
    echo "Remote branch 'master' exists. Pulling..."
=======
    echo "分支已存在"
>>>>>>> 6937f09 (推送默认分支)
    # 先 fetch，再创建本地分支并跟踪
    git fetch origin master || { echo "Fetch failed. Check network or permissions."; exit 1; }
    git checkout master
    # 如果远程有提交，本地会同步；如果无提交，本地为空
  else
    echo "Remote branch 'master' does not exist. Creating local master..."
    git checkout -b master
    # 创建空提交，避免 push 时没有提交
    git commit --allow-empty -m "创建空提交"
  fi
fi


# 添加文件
git add .

# 检查是否有变更
if ! git diff-index --quiet HEAD --; then
  echo "Committing changes..."
  git commit -m "提交更新"
else
  echo "No changes to commit."
fi

# ✅ 关键：先拉取远程更新，避免 non-fast-forward
if git fetch origin master 2>/dev/null; then
  # 检查是否需要合并
  if ! git diff --quiet HEAD origin/master; then
    echo " 存在远程更新，尝试 rebase..."
    if ! git pull --rebase origin master; then
      echo " 合并失败，尝试手动解决冲突"
      exit 1
    fi
  fi
fi

# 推送
echo "尝试推送更新到远程 master 分支..."
git push -u origin master

if [ $? -eq 0 ]; then
  echo "✅ Git 推送 master 成功"
else
  echo "❌ Git 推送 master 失败"
  # 可选：失败时提示用户手动处理
<<<<<<< HEAD
  echo "Hint: Run 'git pull --rebase origin master' and resolve conflicts, then push again."
=======
>>>>>>> 6937f09 (推送默认分支)
  exit 1
fi